package com.example.redisstudy.concurrent;

import com.example.redisstudy.pojo.RespondBean;

import java.util.Arrays;
import java.util.List;
import java.util.concurrent.*;
import java.util.stream.Collectors;

/**
 * @Classname completefutureTest
 * @Description TODO
 * @Version 1.0.0
 * @Date 2024/3/4 17:10
 * @Created by ligan
 */
public class completefutureTest {
    private static final int THREAD_POOL_SIZE = 10;

    public RespondBean updateCache(Product inputProduct) {
        RespondBean rb = new RespondBean();
        StringBuilder resultMessage = new StringBuilder();
        List<String> productIdList = Arrays.asList(inputProduct.PRODUCT_ID.split(","));
        ExecutorService executor = Executors.newFixedThreadPool(THREAD_POOL_SIZE);

        List<CompletableFuture<Void>> futures = productIdList.stream()
                .map(productId -> CompletableFuture.runAsync(() -> {
                    try {
                        // Your existing logic here
                        // Update resultMessage, callServer method, etc.
                    } catch (Exception e) {
                        resultMessage.append(productId).append(": Error - ").append(e.getMessage()).append("\n");
                    }
                }, executor))
                .collect(Collectors.toList());

        CompletableFuture<Void> allOf = CompletableFuture.allOf(futures.toArray(new CompletableFuture[0]));
        try {
            allOf.get(60, TimeUnit.SECONDS); // Wait for all tasks to complete
            rb.FLAG = true;
            rb.MESSAGE = "更新缓存成功！\n" + resultMessage.toString();
        } catch (InterruptedException | ExecutionException | TimeoutException e) {
            rb.FLAG = false;
            rb.MESSAGE = "更新缓存失败！\n" + e.getMessage();
            e.printStackTrace(); // Log the exception
        } finally {
            executor.shutdown();
        }

        return rb;
    }

    public class Product{
        public String PRODUCT_ID;
    }
}




class Main {
    public static void main(String[] args) {
        ExecutorService executor = Executors.newFixedThreadPool(2);

        Future<String> future1 = executor.submit(() -> {
            Thread.sleep(10000); // 模拟耗时操作
            return "Task 1 Result";
        });

        Future<String> future2 = executor.submit(() -> {
            Thread.sleep(1000); // 模拟耗时操作
            return "Task 2 Result";
        });

        try {
            // 获取任务1的执行结果，并打印
            String result1 = future1.get();
            System.out.println("Task 1 Result: " + result1);

            // 获取任务2的执行结果，并打印
            String result2 = future2.get();
            System.out.println("Task 2 Result: " + result2);
        } catch (Exception e) {
            e.printStackTrace();
        }

        executor.shutdown();
    }
}

class main2{

        public static void main(String[] args) {
            int cpuCores = 2;
            ExecutorService executor = Executors.newFixedThreadPool(cpuCores);

            // 现在你可以向 executor 提交任务来执行
            executor.submit(() -> {
                // 你的任务代码
                System.out.println("Task 1 is running on thread: " + Thread.currentThread().getName());
            });

            executor.submit(() -> {
                // 你的任务代码
                System.out.println("Task 2 is running on thread: " + Thread.currentThread().getName());
            });

            // 最后别忘了关闭线程池
            executor.shutdown();
        }

}

